<?php
namespace app\command\service;

use app\command\service\step\CheckIncluded;
use app\command\service\step\CheckKeywords;
use app\command\service\step\CheckLinks;
use app\command\service\step\CheckSSL301;
use app\command\service\step\CheckTplCode;
use Workerman\Worker;
use Workerman\Connection\TcpConnection;

class TaskServer
{
    public static $db;

    public static function start()
    {
        $taskWorker = new Worker('Text://0.0.0.0:19890');
        $taskWorker->count = 8;
        $taskWorker->name = 'TaskWorker';

        $taskWorker->onWorkerStart = function (Worker $worker)
        {
            self::$db = new \Workerman\MySQL\Connection(env('database.hostname'),
                env('database.hostport', 3306), env('database.username'), env('database.password', ''), env('database.database', ''));
        };

        $taskWorker->onMessage = function(TcpConnection $connection, $taskData)
        {
            $taskData = json_decode($taskData, true);

            try {
                switch ($taskData['cmd']) {

                    case 'code':
                        $res = self::codeAnalysis($taskData);
                        break;
                    case 'web':
                        $res = self::webpageAnalysis($taskData);
                        break;
                    case 'keywords':
                        $res = self::keywordsAnalysis($taskData, self::$db);
                        break;
                    case 'links':
                        $res = self::linksAnalysis($taskData, self::$db);
                        break;
                    case 'article':
                        $res = self::articleAnalysis($taskData);
                        break;

                }

                self::$db->update(env('database.prefix') . 'seo_check_task_detail')
                    ->cols([
                        'remark' => json_encode($res),
                        'status' => 2,
                        'update_time' => date('Y-m-d H:i:s')
                    ])
                    ->where('task_id=' . $taskData['task_id'] . ' AND code="' . $taskData['cmd'] . '"')->query();

                $has = self::$db->select('id')->from(env('database.prefix') . 'seo_check_task_detail')
                    ->where('task_id=' . $taskData['task_id'] . ' AND status=1')->row();
                if (empty($has)) {
                    self::$db->update(env('database.prefix') . 'seo_check_task')->cols(array('status'=>'2'))->where("id={$taskData['task_id']}")->query();
                }
            } catch (\Exception $e) {
                if (strpos($e->getMessage(), '404 Not Found') !== false || strpos($e->getMessage(), '503 Service Temporarily Unavailable') !== false) {
                    $connection->send(json_encode(['code' => -1, 'data' => [], 'msg' => '该网站暂时无法访问']));
                } else {
                    $connection->send(json_encode(['code' => -1, 'data' => [], 'msg' => $e->getMessage()]));
                }

                return;
            }

            $connection->send(json_encode($res));
        };

        if (strtoupper(substr(PHP_OS,0,3))==='WIN') {
            Worker::runAll();
        }
    }

    /**
     * 代码分析
     * @param $taskData
     * @return array
     */
    private static function codeAnalysis($taskData)
    {
        $analysis = [];
        // 检测301
        $analysis301 = CheckSSL301::run($taskData);
        // 检测模板代码
        $analysisTplCode = CheckTplCode::run($taskData);

        $analysis = $analysis + $analysis301 + $analysisTplCode;

        return dataReturn(101, '代码分析完成', $analysis);
    }

    /**
     * 网站收录分析
     * @param $taskData
     * @return array
     */
    private static function webpageAnalysis($taskData)
    {
        $analysis = CheckIncluded::run($taskData);

        return dataReturn(102, '收录分析完成', $analysis);
    }

    /**
     * 关键词分析
     * @param $taskData
     * @param $db
     * @return array
     */
    private static function keywordsAnalysis($taskData, $db)
    {
        $analysis = CheckKeywords::run($taskData, $db);

        return dataReturn(103, '关键词分析完成', $analysis);
    }

    /**
     * 导入链接分析
     * @param $taskData
     * @param $db
     * @return array
     */
    private static function linksAnalysis($taskData, $db)
    {
        $analysis = CheckLinks::run($taskData, $db);

        return dataReturn(104, '导入链接分析完成', $analysis);
    }

    /**
     * 文章分析
     * @param $taskData
     * @return array
     */
    private static function articleAnalysis($taskData)
    {
        return dataReturn(105, '文章分析完成');
    }
}
